<template>
  <div>
    <div
      v-for="(item, index) in answerList"
      :key="index"
      v-html="md.render(item.content)"
    ></div>
    <el-button @click="clickfun">按钮</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import MarkdownIt from "markdown-it";
import mermaid from "mermaid";
const md = new MarkdownIt({
  html: true, // 启用HTML标签
  breaks: true, // 转换换行符为<br>
  linkify: true, // 自动转换URL为链接
  typographer: true, // 启用语言中性的替换
});
mermaid.initialize({
  startOnLoad: false, // 不自动渲染页面上的图表
  theme: "default", // 或 'dark' / 自定义主题
  securityLevel: "loose",
  flowchart: {
    htmlLabels: true,
    curve: "linear",
  },
  erDiagram: {
    useMaxWidth: true,
    htmlLabels: true,
  },
});
md.use(function (md) {
  md.renderer.rules.fence = function (tokens, idx, options, env, slf) {
    console.log("tokens", tokens, tokens[idx]);
    if (tokens[idx].info === "mermaid") {
      // 此处判断是否为 mermaidChart 代码块
      const code = tokens[idx].content.trim();
      return `<div id="mermaid-id-${idx}" class="mermaid">${code}</div>`;
    } else if (tokens[idx].info === "think") {
      const code = tokens[idx].content.trim();
      return `<div id="think-id-${idx}" class="think_content">${code}</div>`;
    } else {
      // 其他代码块
      return `<pre><code class='languge-${tokens[idx].info}'>${tokens[idx].content}</code></pre>`;
    }
  };
});
const answerList = ref([
  {
    content:
      "```mermaid\n gantt \n  title 北京五日游时间轴\n  dateFormat  HH:mm\n  axisFormat %H:%M\n  阿斯顿撒大苏打 :   17:49, 2m   \n   Task A : 10m \n Task B : 5m \n  Final milestone : milestone, m2, 18:08, 4m \n```\n",
  },
  // {
  //   content:
  //     "```mermaid\n funnelchart \n  title 行业受冲击程度排序 \n  section 极端脆弱 \n  农业 : 62% \n  沿海房地产 : 58%  \n   保险业 : 55%  \n```\n",
  // },
]);
const clickfun = () => {
  // const timer = setInterval(() => {
  //   answerList.value[answerList.value.length - 1].content += 'asdas啊实'
  //   if (answerList.value[answerList.value.length - 1].content.length >= 100) {
  //     clearInterval(timer)
  //   }
  // }, 100)
  renderMermaidChart();
};
const renderMermaidChart = () => {
  nextTick(() => {
    const mermaidCharts = document.querySelectorAll(".mermaid");
    if (mermaidCharts.length > 0) {
      // 过滤掉非HTMLElement元素并转换为数组
      // mermaid.init(undefined, mermaidCharts);

      mermaid.run({
        nodes: mermaidCharts,
      });
    }
  });
};
onMounted(() => {
  const timer = setInterval(() => {
    answerList.value[answerList.value.length - 1].content += "asdas啊实";
    renderMermaidChart();
    if (answerList.value[answerList.value.length - 1].content.length >= 1000) {
      clearInterval(timer);
    }
  }, 100);
});
</script>

<style lang="scss" scoped>
// :deep(.think_content) {
//   background-color: red;
//   width: 200px;
//   height: 200px;
// }
// :deep(.mermaid) {
//   font-family: "Inter", "Noto Sans SC", "Microsoft YaHei", sans-serif !important;
// }
</style>
